<template>
  <div class="view-fill">
    <div
      class="app-container-flex"
      v-if="!modifyInfo.visible && !receiptDetailsInfo.visible"
    >
      <full-screen
        v-model="showDialog"
        title="手术跟台收货明细"
        :btnList="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-billRegistrationVOList>
                <div
                  v-if="
                    infoList.data.billRegistrationVOList &&
                    infoList.data.billRegistrationVOList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data
                      .billRegistrationVOList"
                    :key="index"
                  >
                    <a
                      class="slip-edit"
                      v-if="index <= 1"
                      @click="showreceiptDetail(item.id)"
                      >{{ item.billCode }}</a
                    >
                    <span
                      v-if="
                        index < 1 &&
                        infoList.data.billRegistrationVOList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.billRegistrationVOList.length > 2"
                    @command="showreceiptDetail"
                  >
                    <span class="el-dropdown-link slip-edit">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in infoList.data.billRegistrationVOList"
                          :key="item.id"
                          :command="item.id"
                          >{{ item.billCode }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('detailInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tabIndex="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :mergeData="tableInfo.mergeData"
                :mergeFiled="tableInfo.mergeFiled"
                :summaryFieldList="tableInfo.summaryFieldList"
                :isDynamic="true"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </full-screen>
    </div>
    <individual-details
      v-if="showIndividualDetails"
      v-model:show-dialog="showIndividualDetails"
      :query="paramsIndividual"
      :info="productInfo"
    ></individual-details>
    <surgery-and-table-receipt-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
    />
    <purch-receipt-detail
      v-if="receiptDetailsInfo.visible"
      v-model:visible="receiptDetailsInfo.visible"
      :title="receiptDetailsInfo.title"
      :id="receiptDetailsInfo.id"
    />
  </div>
</template>

<script setup name="checkPrice">
import FullScreen from '@/components/FullScreen/index'
import PageTable from '@/components/PageTable/index'
import {
  withTableReceivingOrderDetail,
  withTableReceivingOrderDetailAll,
  withTableReceivingOrderPrint,
  withTableReceivingExportOrders,
  withTableReceivingOrderCheckPrice,
} from '@/api/stock'
import { orderAffairAll } from '@/api/affair'
import BasicInformation from '@/components/BasicInformation/index'
import IndividualDetails from './IndividualDetails'
import SurgeryAndTableReceiptModify from '@/views/stock/surgeryAndTableReceipt/modify'
import PurchReceiptDetail from '../../purch/receipt/details.vue'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id'])

const infoList = reactive({
  data: {},
  fieldList: [
    { label: '收货单号', value: 'orderNo' },
    { label: '供应商', value: 'supplierName' },
    { label: '仓库', value: 'depotName' },
    { label: '消耗开始时间', value: 'consumeTimeGreater' },
    { label: '消耗结束时间', value: 'consumeTimeLess' },
    { label: '收货人', value: 'receivingUserName' },
    { label: '收货时间', value: 'receivingTime' },
    { label: '入库人', value: 'storageUserName' },
    { label: '入库时间', value: 'storageTime' },
    { label: '状态', value: 'statusValue' },
    {
      label: '收票单号',
      value: 'billRegistrationVOList',
      type: 'slot',
      className: 'not-br',
    },
    { label: '备注', value: 'remark' },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    receivingId: props.id,
  },
})
const fullInfo = reactive({
  btnList: [
    // { label: "打印", event: print, show: true },
    // { label: "导出excel", event: exportExcel, show: true },
    { label: '保存', event: save, show: true },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  mergeData: {},
  // mergeFiled: ["licenseNumber", "commonName", "type", "standard"],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'totalPrice', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      width: 220,
    },
    {
      label: '规格\n计量单位',
      value: 'standard',
      type: 'slot',
    },
    // {
    //   label: "消耗数量",
    //   value: "consumeQty",
    //   type: "column",
    //   formatter: proxy.$fn.qtyFormatter
    // },
    // {
    //   label: "消耗单价",
    //   value: "consumePrice",
    //   type: "column",
    //   formatter: proxy.$fn.TripartiteMethod,
    // },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      width: 150,
    },
    {
      label: '收货数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '结算单价',
      value: 'checkPrice',
      type: 'money',
      rules: { validator: proxy.$validate.positiveMoneyZero, trigger: 'blur' },
    },
    {
      label: '金额',
      value: 'totalPrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      width: 220,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: singleProductDetails,
        show: true,
      },
    ],
  },
})
const affairTableInfo = reactive({
  api: orderAffairAll,
  query: {
    orderType: 'with_table_receiving_order',
    orderId: props.id,
    sort: 'operate_time desc',
  },
})

const modifyInfo = reactive({
  visible: false,
  id: props.id,
  title: '修改',
})
const receiptDetailsInfo = reactive({
  id: '',
  visible: false,
})

const showIndividualDetails = ref(false)
const paramsIndividual = ref({})
const productInfo = ref({})
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canUpdate = computed(() => {
  return (
    proxy.$permission('surgeryAndTableReceipt:update') &&
    infoList.data.status === 'pend_submit'
  )
})

watch(
  () => props.visible,
  () => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)

watch(
  () => tableInfo.data,
  () => {
    tableInfo.mergeData = proxy.$fn.getMergeData(val)
    tableInfo.data.forEach(
      (row) => (row.totalPrice = (row.qty || 0) * (row.price || 0))
    )
  },
  {
    deep: true,
  }
)

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm']]
  proxy.$nextTick(() => {
    getMain()
  })
})

function singleProductDetails(row) {
  const params = {
    receivingId: props.id,
    price: row.price,
    productId: row.productId,
  }
  productInfo.value = row
  paramsIndividual.value = params
  showIndividualDetails.value = true
}
function getMain() {
  withTableReceivingOrderDetail(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
  withTableReceivingOrderDetailAll(filterInfo.query).then((res) => {
    if (res) {
      tableInfo.data = res.data
    }
  })
}

// 触发事件
function handleEvent() {
  // switch (event) {
  //     // 对表格获取到的数据做处理
  // }
}
//打印
function print() {
  withTableReceivingOrderPrint(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printInOrder(resp.data)
    }
  })
}
//导出excel
function exportExcel() {
  withTableReceivingExportOrders(infoList.data.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function update() {
  modifyInfo.visible = true
}
function showreceiptDetail(id) {
  receiptDetailsInfo.visible = true
  receiptDetailsInfo.id = id
}
function save() {
  const data = infoList.data
  const details = tableInfo.data
  proxy.$fn.checkForm(formRefs.value).then(() => {
    data.details = details
    const api = withTableReceivingOrderCheckPrice
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
      }
    })
  })
}
</script>

<style scoped></style>
